package com.sky.aspect;


import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.entity.Dish;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

import static com.sky.constant.AutoFillConstant.*;
import static com.sky.enumeration.OperationType.INSERT;
import static com.sky.enumeration.OperationType.UPDATE;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {

    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    public void pt() {
    }

    ;

    @Before("pt()")
    //JoinPoint 会封装方法的所有信息
    public void autoFillAspectAdvice(JoinPoint joinPoint) {
        log.info("执行切面通知方法=========================-====================");
        //公共字段填充
        //1.获取切入方法的参数
        Object[] args = joinPoint.getArgs();//获取方法的参数
        if (args == null || args.length != 1) {
            return;
        }
        Object entity = args[0];
        //2.准备需要赋的数据  当前创建人 创建时间
        Long currentId = BaseContext.getCurrentId();
        LocalDateTime now = LocalDateTime.now();
        //3.获取注解中方法的返回值判断是新增还是修改
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//获取方法的签名
        Method method = signature.getMethod();//获取方法对象
        AutoFill annotation = method.getAnnotation(AutoFill.class);//获取注解
        OperationType value = annotation.value();
        try { //4.赋值 判断是新增还是修改
        if (value.equals(INSERT)) {
                //给创建人创建时间修改人修改时间赋值
                //反射赋值
            Method setCreateTime = entity.getClass().getDeclaredMethod(SET_CREATE_TIME, LocalDateTime.class);
            Method setCreateUser = entity.getClass().getDeclaredMethod(SET_CREATE_USER, Long.class);
            setCreateTime.invoke(entity, now);
            setCreateUser.invoke(entity, currentId);
        }
        Method setUpdateTime = entity.getClass().getDeclaredMethod(SET_UPDATE_TIME, LocalDateTime.class);
        setUpdateTime.invoke(entity, now);
        Method setUpdateUser = entity.getClass().getDeclaredMethod(SET_UPDATE_USER, Long.class);
        setUpdateUser.invoke(entity, currentId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
